package com.yand.serviceimpl.login;


import com.yand.api.entity.exception.LoginErrorException;
import com.yand.api.entity.system.TSysMenu;
import com.yand.api.entity.system.TSysUser;
import com.yand.api.service.login.LoginService;
import com.yand.api.service.system.MenuService;
import com.yand.api.service.system.RoleService;
import com.yand.api.util.SpringBeanFactoryUtils;
import com.yand.mapper.system.TSysUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private TSysUserMapper sysUserMapper;

    @Autowired
    private RoleService roleService;




    @Autowired
    private MenuService menuService;

    /**
     * 1, 获取验证码进行验证码进行校验
     * 2, 登录逻辑进行校验
     * @param user
     */
    @Override
    public void doLogin(TSysUser user) {

        String authCode = user.getAuthcode();

        String randdomCode = (String)SpringBeanFactoryUtils.getRequest().getSession().getAttribute("authcode");

        if(!authCode.toLowerCase().equals(randdomCode.toLowerCase())){
            throw new LoginErrorException("验证码输入错误");
        }

        try{
            Subject subject = SecurityUtils.getSubject();

            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUserCode(),user.getRPassword());

            //具体逻辑由 MyShiroRealm 实现
            subject.login(usernamePasswordToken);

        }catch(IncorrectCredentialsException e){

            throw new LoginErrorException(e.getMessage());
        }

    }

    /**
     * 通过usercode查询 User对象
     * @param userCode
     * @return
     */
    @Override
    public TSysUser getUserByCode(String userCode) {
        TSysUser user = new TSysUser();
        user.setUserCode(userCode);
        List<TSysUser> sysUserList = sysUserMapper.selectUsers(user);
        if(sysUserList.size() == 0){
            return null;
        }
        return sysUserList.get(0);

    }

    @Override
    public List<TSysMenu> getMenuTreeList(int roleId) {

        List<TSysMenu> menuList = roleService.getMenuListByRoleId(roleId);
        //从list中获取 checked 为 true 的 记录
        menuList = menuList.stream().filter(m -> m.isChecked()== true).collect(Collectors.toList());

        return menuService.convertTreeJsonList(menuList);
    }
}
